// pages/clickMe/plan/addlayout.js
import { API_HOST_1 } from '../../../api/config'
import { CHINA_NORTH_REGION } from '../../../store/region'
import api from '../../../api/index'
import { userInfoStore } from '../../../store/userInfo'
const app = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    hasRelationShop: false,
    pshow: false,
    cshow: false,
    dshow: false,
    plist: [],
    clist: [],
    dlist: [],
    privince: {},
    city: {},
    district: {},
    objectArray: CHINA_NORTH_REGION,

    housePlanId: null,
    shoplist: [],
    images:[],
    uploads:[],
    uploading:[],
    selectshop: 0,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let self = this
    if (options.id){
      this.setData({ housePlanId: options.id },()=>{
        api.getUserHouseImage({ housePlanId: options.id}).then(res => {
          let {result} = res;
          self.setData({
            images: result.images,
            uploads: result.images.slice(),
            selectshop: result.distributorId
          })
        })
      })
    } else {
      api.getuserrelationshop({ openId: userInfoStore.userInfo.openId }).then(res => {
        let { result } = res;
        if (result.length > 0) {
          self.setData({ shoplist: result, hasRelationShop: true });
        }
      })
    }
    
  },

  onShow: function () {

  },

  chooseImage:function(){
    let self=this
    wx.chooseImage({
      count: 9, // 默认9
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        // console.log(JSON.stringify(res))
        wx.showLoading()
        var tempFilePaths = res.tempFilePaths
        let count = 0
        tempFilePaths.forEach((image, index) => {
          
          wx.uploadFile({
            url: API_HOST_1 + 'daikin/upload/add',
            filePath: image,
            name: 'image',
            success(res) {
              if (res.statusCode == 200) {
                let data = JSON.parse(res.data);
                self.data.uploads.push({ uri: data.result});
                self.data.images.push({ uri: image})
                self.setData({ 
                  images: self.data.images, 
                  uploads: self.data.uploads
                })
              }
            },
            complete() {
              count++;
              if (tempFilePaths.length == count) {
                wx.hideLoading()
              }
            }
          })
        });
      }
    })
  },

  delImage: function(e){
    let idx = e.currentTarget.dataset.index;
    this.data.images.splice(idx,1)
    this.data.uploads.splice(idx, 1)
    this.setData({
      images: this.data.images,
      uploads: this.data.uploads
    })
  },

  getShopList: function () {
    let param = {
      province: (this.data.privince.regname ? this.data.privince.regname : ''),
      city: (this.data.city.regname ? this.data.city.regname : ''),
      district: (this.data.district.regname ? this.data.district.regname : '')
    }
    let self = this;
    api.getshoplist(param).then(res => {
      self.setData({ shoplist: res.result, selectshop: 0});
    });
  },

  selectByParid: function (pid) {
    let list = [];
    for (var i = 0; i < this.data.objectArray.length; i++) {
      if (this.data.objectArray[i].parid == pid) {
        list.push(this.data.objectArray[i])
      }
    }
    return list;
  },

  selectByParid1: function (pid) {
    let list = [];
    for (var i = 0; i < this.data.adrArray.length; i++) {
      if (this.data.adrArray[i].parid == pid) {
        list.push(this.data.adrArray[i])
      }
    }
    return list;
  },

  selectTap: function (e) {
    let idx = e.currentTarget.dataset.idx;
    if (idx == 1) {
      if (!this.data.pshow) {
        let list = this.selectByParid("1");
        this.setData({
          pshow: !this.data.pshow,
          plist: list,
          clist: [],
          dlist: [],
          privince: {},
          city: {},
          district: {}
        })
      } else {
        this.setData({
          pshow: !this.data.pshow
        })
      }
    }
    if (idx == 2 && this.data.privince.regid) {
      if (!this.data.cshow) {
        let list = this.selectByParid(this.data.privince.regid);
        this.setData({
          cshow: !this.data.cshow,
          clist: list,
          dlist: [],
          city: {},
          district: {}
        })
      } else {
        this.setData({
          cshow: !this.data.cshow
        })
      }
    }
    if (idx == 3 && this.data.city.regid) {
      if (!this.data.dshow) {
        let list = this.selectByParid(this.data.city.regid);
        this.setData({
          dshow: !this.data.dshow,
          dlist: list,
          district: {}
        })
      } else {
        this.setData({
          dshow: !this.data.dshow
        })
      }
    }
  },

  optionTap: function (e) {

    let idx = e.currentTarget.dataset.idx;
    let index = e.currentTarget.dataset.index;
    let self = this;
    if (idx == 1) {
      this.setData({
        privince: this.data.plist[index],
        pshow: !this.data.pshow,
        selectshop: 0
      }, () => {
        self.getShopList();
      });
    }
    if (idx == 2) {
      this.setData({
        city: this.data.clist[index],
        cshow: !this.data.cshow,
        selectshop: 0
      }, () => {
        self.getShopList();
      });
    }
    if (idx == 3) {
      this.setData({
        district: this.data.dlist[index],
        dshow: !this.data.dshow,
        selectshop: 0
      }, () => {
        self.getShopList();
      });
    }
  },

  radioChange: function (e) {
    this.setData({ selectshop: e.detail.value });
  },

  save:function(){
    if (!this.data.housePlanId && this.data.selectshop == 0) {
      wx.showToast({
        icon: "none",
        title: "请选择服务商!"
      })
      return;
    }
    if (this.data.images.length <=0) {
      wx.showToast({
        icon: "none",
        title: "请上传图片!"
      })
      return;
    }
    let list = [];
    let image;
    for (let i = 0; i < this.data.uploads.length;i++){
      image = this.data.uploads[i];
      list.push(image.uri);
    }
    
    let param = {
      distributorId: this.data.selectshop,
      userId: userInfoStore.userInfo.id,
      images: list
    }

    if (this.data.housePlanId){
      param = Object.assign(param, { housePlanId: this.data.housePlanId})
      api.updateUserHouseImages(param).then(res => {
        if (res.success) {
          var pages = getCurrentPages();
          var prevPage = pages[pages.length - 2];
          prevPage.setData({ isBack:true},()=>{
            wx.navigateBack();
          })
        }
      })

    }
    else
    api.saveUserHouseImages(param).then(res => {
      if(res.success) {
        var pages = getCurrentPages();
        var prevPage = pages[pages.length - 2];
        prevPage.setData({ isBack: true }, () => {
          wx.navigateBack();
        })
      }
    })

  },


})